package com.fashion.service;

import com.fashion.dao.VideoDao;
import com.fashion.model.Video;
import com.fashion.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-4-12
 * Time: 下午4:46
 */
@Service("videoService")
public class VideoServiceImpl implements VideoService {
    private VideoDao videoDao;

    @Override
    public void saveOrUpdate(Object object) {
        videoDao.saveOrUpdate(object);
    }

    @Override
    public void deleteEntityById(String id) {
        videoDao.deleteById(id, Video.class);
    }

    @Override
    public void deleteEntity(Object object) {
        videoDao.delete(object);
    }

    @Resource(name = "videoDao")
    public void setVideoDao(VideoDao videoDao) {
        this.videoDao = videoDao;
    }

    @Override
    public List<Video> searchVideos(String name, int page, int rows) {
        StringBuilder hql = new StringBuilder("from Video v ");
        Map<String, Object> parameters = prepareParameters(name,hql);

        return videoDao.findItemsWithPage(hql.toString(), parameters, page, rows);
    }

    @Override
    public int countVideos(String name, int page, int rows) {
        StringBuilder basicHql = new StringBuilder("select count(v.id) " +
                "from Video v");

        Map<String, Object> parameters = prepareParameters(name, basicHql);

        return videoDao.countItems(basicHql.toString(), parameters);
    }

    @Override
    public Video findVideoById(String id) {
        return videoDao.getEntityById(Video.class,id);
    }

    @Override
    public void deleteVideoById(String id) {
        videoDao.deleteById(id,Video.class);
    }

    protected Map<String, Object> prepareParameters(String name,StringBuilder basicHql) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        if (!StringUtils.isNullOrEmpty(name)) {
            basicHql.append(" where v.name like :name ");
            parameters.put("name", "%" + name + "%");
        }

        basicHql.append(" order by v.createDateTime desc");

        return parameters;
    }
}
